<template>
  <!-- 筛选区域 -->
  <div class="container">
    <sub-cate-filter :data="subCategory"
                     :search="search"/>
  </div>

  <div class="show container">
    <!-- 排序区域 -->
    <cate-goods-sort @sort-change="search"/>

    <!-- 商品展示区域 -->
    <cate-show-goods :data="goods"
                     :load-more="loadMore"/>
  </div>
</template>

<script lang="ts"
        setup>
import {getSubCategory, getSubGoods} from '@/api/category'
import CateGoodsSort from '@/components/library/CateGoodsSort.vue'
import CateShowGoods from '@/components/library/CateShowGoods.vue'
import SubCateFilter from '@/components/library/SubCateFilter.vue'
import {useCommonStore} from '@/stores/common'
import type {SubCategory} from '@/types/category'
import type {Path} from '@/types/common'
import type {Good} from '@/types/good'
import {storeToRefs} from 'pinia'
import {ref, watch} from 'vue'
import {onBeforeRouteLeave, useRoute} from 'vue-router'

let route = useRoute()
let commonStore = useCommonStore()
let {pathList} = storeToRefs(commonStore)

let subCategory = ref<SubCategory>({})
let canLoadGood: boolean = false

let stopWatch = watch(() => route, () => {
  requestAll()
}, {
  immediate: true,
  deep: true
})

onBeforeRouteLeave(() => {
  stopWatch()
})

// 发起所有接口请求
function requestAll(): void {
  canLoadGood = false
  Promise.all([
    getSubCategory(<string>route.params.id)
  ]).then(([subRes]) => {
    initSubCategory(subRes)
    canLoadGood = true
    getGoods()
  })
}

function initSubCategory(res: any): void {
  subCategory.value = <SubCategory>res.result
  subCategory.value.brands?.unshift({id: '-1', name: '全部'})
  subCategory.value.saleProperties?.forEach(
    (item) => item.properties?.unshift({id: '-1', name: '全部'})
  )
  let parent: Path = {
    name: subCategory.value.parentName ?? '',
    path: `/category/${subCategory.value.parentId}`
  }
  let thisPath: Path = {
    name: subCategory.value.name ?? '',
    path: ''
  }
  pathList.value = [pathList.value[0], parent, thisPath]
}


// 搜索
let goods = ref<Good[]>([])
let page: number = 1
let total: number = 0
let pageSize: number = 20
let filterData: any = {}

async function getGoods(): Promise<void> {
  let res: any = await getSubGoods({
    ...filterData,
    page,
    pageSize
  })
  goods.value = goods.value.concat(<Good[]>res.result.items)
  total = <number>res.result.pages
}

function search(data: any): void {
  page = 1
  goods.value = []
  // 合并现有筛选参数
  filterData = {
    ...filterData,
    ...data
  }
}

// 加载更多，返回true或false，true为加载成功，false为没有更多
async function loadMore(): Promise<boolean> {
  if (page + 1 > total || !canLoadGood) return false
  page++
  await getGoods()
  return true
}
</script>

<style lang="less"
       scoped>
.show {
  padding: 0 25px;
  margin: 25px auto;
  background-color: #ffffff;
}
</style>